<!--
* description: 备件价格新增审核
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :dynamic-page-size="50"
      :page-size-array="[50, 100, 200, 400]"
      :dynamic-cell-style="columnStyle"
      :callback-obj="callbackObj"
    >
      <!--      成本价 -->
      <template #costPrice="scope">
        <span>
          {{ scope.row['costPrice'] | fixTwo }}
        </span>
      </template>
      <!--      建议零售价 -->
      <template #userPrice="scope">
        <span>
          {{ scope.row['userPrice'] | fixTwo }}
        </span>
      </template>
      <!--      紧急订单价 -->
      <template #urgentOrderPrice="scope">
        <span>
          {{ scope.row['urgentOrderPrice'] | fixTwo }}
        </span>
      </template>
      <!--      网点利润率 -->
      <template #outletProfitMargin="scope">
        <span
        >
          {{ scope.row['outletProfitMargin'] | percentage }}
        </span>
      </template>
      <!--      总部利润率 -->
      <template #headquartersProfitMargin="scope">
        <span
          v-show="scope.row['headquartersProfitMargin'] !== null && scope.row['headquartersProfitMargin']"
        >
          {{ scope.row['headquartersProfitMargin'] | percentage }}
        </span>
      </template>
    </one-table-template>

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data-list="selectiondata"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/apiBaseData'
import { orgApis } from '@/api/pabasicdataapi'
import { exportExcel } from '@/utils/getTimeString.js'
import Vue from 'vue'

export default {
  name: 'PricePartsExamine',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  filters: {
    // 小数转换百分比显示
    percentage: function(num) {
      if (!num) return ''
      return (Number(num) * 100).toFixed(2) + '%'
    },
    fixTwo: function(val) {
      return Number(val).toFixed(2)
    }
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next(vm => { vm.queryTable(1) })
    })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      icon: 'el-icon-arrow-down',
      status: false,
      // editRowData: {},
      selectiondata: [],
      // 网格查询API配置对象
      apiConfig: api.queryAddSparePartReviewList,
      columnStyle({ row, column, rowIndex, columnIndex }) {
        // 颜色 红 -- 黄 -- 绿
        const bg = {
          red: 'background:#eb4d4b !important',
          yellow: 'background:#f9ca24 !important',
          green: 'background:#badc58 !important'
        }
        // 低于最低阈值时，标红；不在区间内，但高于最低阈值，标黄；
        function handleProfit({ range: [low, high], min }, value, prop) {
          if (value < min) {
            return bg.red
          } else if (value > min && value < low) {
            return bg.yellow
          } else if (value >= low && value <= high) {
            return bg.green
          } else {
            return bg.yellow
          }
        }
        // dlrProfitMarginH  dlrProfitMarginL  网点利润率区间
        // oemProfitMarginH  oemProfitMarginL  总部利润率区间
        // dlrProfitMarginMin 网点最低利润率
        // oemProfitMarginMin 总部最低利润率
        if (column.property === 'headquartersProfitMargin') {
          return handleProfit({
            range: [row['oemProfitMarginL'], row['oemProfitMarginH']],
            min: row['oemProfitMarginMin']
          }, Number(row['headquartersProfitMargin']), 'headquartersProfitMargin'
          )
        }
        if (column.property === 'outletProfitMargin') {
          return handleProfit({
            range: [row['dlrProfitMarginL'], row['dlrProfitMarginH']],
            min: row['dlrProfitMarginMin']
          }, Number(row['outletProfitMargin']), 'outletProfitMargin'
          )
        }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        // {
        //   compKey: 'btnKey3',
        //   type: '',
        //   size: 'small',
        //   name: 'add',
        //   clickEvent: this.add,
        //   text: this.$t('sys.button.add'), // 新增
        //   position: 'left'
        // },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          disabled: true,
          parentFileds: 'disabled:table',
          clickEvent: () => this.pass('1'),
          text: '通过', // 新增
          name: 'adopt',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          disabled: true,
          parentFileds: 'disabled:table',
          type: '',
          size: 'small',
          clickEvent: () => this.pass('0'),
          text: '驳回', // err
          name: 'reject',
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey6',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey7',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              textField: 'partRepairTypeName',
              customObj: {
                api: api.queryPartRepairs
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称码：',
              codeField: 'partNameCn',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '备件状态：',
              codeField: 'partStatus',
              customObj: {
                api: api.queryPartStatus
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey4',
              labelName: '供应商：',
              codeField: 'supplierCode',
              textField: 'supplierShortName',
              component: () => import('@/components/ve/multipleSearchInput'),
              type: 'inputText',
              isMust: false,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商简称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey3',
                    labelName: '状态：',
                    codeField: 'isEnable',
                    component: () => import('@/components/org/LookupValue'),
                    oFields: 'statusId,statusText',
                    options: [
                      { statusId: '1', statusText: '启用' },
                      { statusId: '0', statusText: '禁用' }
                    ],
                    type: 'dropdownList',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [

                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商简称'
                  },
                  {
                    prop: 'supplierFullName',
                    label: '供应商全称'
                  },
                  {
                    prop: 'supplierAddr',
                    label: '详细地址'
                  },
                  {
                    prop: 'linkMan',
                    label: '联系人'
                  },
                  {
                    prop: 'linkManTel',
                    label: '联系电话'
                  },
                  {
                    prop: 'isEnableCn',
                    label: '状态'
                  },
                  {
                    prop: 'remark',
                    label: '备注'
                  }
                ],
                returnField: {
                  prop: 'supplierCode',
                  label: '供应商编码'
                },
                formField: {
                  supplierCode: '',
                  supplierShortName: '',
                  isEnable: ''
                },
                api: orgApis.supplierInformationQueryquery
              },
              span: 6
            },

            {
              compKey: 'compKey8',
              labelName: '适用车型：',
              codeField: 'carConfigCn',
              component: () => import('@/views/pa/paBasicData/pricePartsAdd/carName/index'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '有替代件',
              codeField: 'replacePiece',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '是' },
                { statusId: '0', statusText: '否' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey10',
              labelName: '审核状态',
              codeField: 'reviewStatus',
              customObj: {
                api: api.queryPartPriceAuditType
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            }
            //   {
            //   compKey: 'compKey11',
            //   span: 18,
            //   codeField: 'orderStatus',
            //   isMul: true,
            //   component: () => import('@/components/org/checkBox/pa_checkGroup.vue'),
            //   type: '',
            //   isMust: false
            // }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partPriceId',
              label: '备件价格ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partPriceReviewId',
              label: '备件价格审核ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'reviewStatus',
              label: '审核状态',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'isEnable',
              label: '是否启用',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },
            {
              prop: 'costPrice',
              label: '标准成本价'
            },
            {
              prop: 'pointPriceNotTax',
              label: '正常订单价'
            },
            {
              prop: 'urgentOrderPriceNotTax',
              label: '紧急订单价'
            },
            {
              prop: 'userPrice',
              label: '建议零售价',
              isSlot: true
            },
            {
              prop: 'headquartersProfitMargin',
              label: '总部利润率',
              isSlot: true
            },
            {
              prop: 'outletProfitMargin',
              label: '正常订单利润率',
              isSlot: true
            },
            {
              prop: 'partRepairTypeName',
              label: '维修类型'
            },
            {
              prop: 'partNameId',
              label: '备件名称码'
            },
            {
              prop: 'carConfigIdList',
              label: '适用车型'
            },
            {
              prop: 'partStatusCn',
              label: '备件状态'
            },
            {
              prop: 'reviewStatusName',
              label: '审核状态'
            },
            {
              prop: 'remark',
              label: '审核意见'
            }
          ],
      callbackObj: {
        // 手动勾选时
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection;
        // },
        onCheckSelectChange: (selection) => {
          this.selectiondata = selection
          this.onCheckSelectChange1(selection)
        }
      },
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          partRepairType: '',
          partNameCn: '',
          partStatus: '',
          supplierCode: '',
          partNo: '',
          partName: '',
          carConfigCn: '',
          carConfigIdList: '',
          replacePiece: '',
          reviewStatus: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.orderStatus': {
      deep: true,
      handler: function(newV, oldV) {
        console.log('watch中：', newV)
        // this.querybystatus(newV)
        this.queryTable()
      }
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    exportExcel111() {
      exportExcel(this.formField, api.exportRejectSparePartPrice.APIUrl, api.exportRejectSparePartPrice.ServiceCode, '备件价格新增审核')
    },
    onCheckSelectChange1(selection) {
      var btn1 = this.tableButtons[2]
      var btn2 = this.tableButtons[3]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
      btn2.disabled = !isCheck
    },
    // 批量驳回、通过
    pass(type) {
      if (type === '0') {
        this.editPopupsState = 'edit'
        this.editPopupsVisible = true
      } else if (type === '1') {
        const that = this
        this.$refs.multipleTable.listLoading = true
        const queryObj = {
        // api配置
          apiConfig: api.auditSparePartPrice,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: this.selectiondata
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then(response => {
          this.$message({
            message: response.msg,
            duration: 2000
          })
          if (response.result === '1') {
            this.$refs.multipleTable.listLoading = false
            this.queryTable()
          }
        })
      }
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
